import { ref } from "vue";
import { defineStore } from "pinia";
import { getSession, setSession } from "@/utils/auth";

let routerList = "";
export const topnavStore = defineStore(
  "topnavStore",
  () => {
    const staticPathList = [{ name: "工作台", path: "/index", query: {} }];
    const topTagsList = ref<any>([...staticPathList]);

    /**
     * @function getList 获取存储在storage中的数据
     * */
    const getList = () => {
      topTagsList.value = JSON.parse(getSession(routerList)) || [
        ...staticPathList,
      ];
      return topTagsList.value;
    };
    const addList = (page: any) => {
      if (page.path == "/index") return;
      let isContain = false;
      if (topTagsList.value.length) {
        for (let i = 0; i < topTagsList.value.length; i++) {
          if (topTagsList.value[i].path == page.path) {
            topTagsList.value[i] = page;
            isContain = true;
          }
        }
      }
      if (!isContain) {
        topTagsList.value.push(page);
      }
      setSession(routerList, JSON.stringify(topTagsList.value));
    };
    const delList = (path: any) => {
      if (path == "/index") return;
      let prevEl = 0;
      const results = topTagsList.value?.filter((el: any, index: number) => {
        prevEl = index - 1;
        return el.path != path;
      });
      topTagsList.value = results;
      setSession(routerList, JSON.stringify(topTagsList.value));
    };
    return {
      topTagsList,
      getList,
      addList,
      delList,
    };
  },
  { persist: { type: "local" } }
);
